import request from '@/utils/Request.js'
import {getLocalStroage} from "@/utils/LocalStroageUtil";
import {ElMessage} from "element-plus";

/**
 * 加载文件元数据
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const loadFilesApi = (data) => {
    return request.get('/file-core/search-all', {
        params: {
            ownerId: getLocalStroage().userId,
            filePath: data.filePath,
            current: data.current,
            size: data.size,
            fileType: data.fileType,
            status: data.status,
        }
    })
}

/**
 * 新建文件夹
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const createNewFolderApi = (data) => {
    return request.post('/file-core/create-new-folder', data)
}

/**
 * 上传文件到HDFS
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const uploadFileToHDFSApi = (data) => {
    return request.put('/file-core/upload-file-to-hdfs', data)
}

/**
 * 新建文件（非文件夹）--弃用
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
// export const createNewFileApi = (data) => {
//     return request.post('/file-core/create-new-file', data)
// }

/**
 * 彻底删除文档
 * @param fileId
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const deleteDocumentApi = (fileId) => {
    return request.delete('/file-core/delete-document', {
        params: {
            fileId: fileId,
        }
    })
}

/**
 * 下载HDFS文件
 * @param fileId HDFS文件ID
 * @param fileName 文件名
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const downloadFromHDFSApi = async (fileId, fileName) => {
    try {
        const response = await fetch(`http://localhost:8888/files/download-from-hdfs/${fileId}/${fileName}`, {
            method: 'GET',
            credentials: 'include'
        });

        if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);

        // 简化文件名解析逻辑（使用可选链操作符）
        const contentDisposition = response.headers.get('content-disposition');
        const fileNameFromHeader = contentDisposition?.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)?.[1]?.replace(/['"]/g, '');
        const finalFileName = fileNameFromHeader || fileName;

        const blob = await response.blob();
        if (blob.size === 0) throw new Error('下载的文件内容为空');

        // 简化下载链接创建流程
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = finalFileName;
        document.body.appendChild(link);
        link.click();
        
        // 立即清理资源（多数浏览器支持同步移除）
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        return { success: true, message: '下载成功' };
    } catch (error) {
        ElMessage.error(`下载失败: ${error.message}`);
        return { success: false, message: error.message };
    }
};

/**
 * 修改文件夹信息
 * 名称
 * 共享状态
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const updateDocumentApi = (data) => {
    return request.put('/file-core/update-document', data)
}

/**
 * 创建共享链接
 * @param data
 */
export const createNewFileShareLinkApi = (data) => {
    return request.post('/share-file/create-file-share-link', data)
}